package cn.kust.chat;

import cn.kust.chat.service.ChatService;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.stream.ChunkedWriteHandler;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication(scanBasePackages = "cn.kust.chat")
@MapperScan("cn.kust.chat.mapper")
public class ServiceChatApplication implements ApplicationRunner {

    @Value("${server.ws.port}")
    private Integer port;

    @Autowired
    private ChatService chatService;

    public static void main(String[] args) {
        SpringApplication.run(ServiceChatApplication.class, args);
    }

    /**
     * 启动netty服务
     *
     * @param args
     * @throws Exception
     */
    @Override
    public void run(ApplicationArguments args) throws Exception {
        // 启动netty服务，并设置ws接口为
        //创建主从线程池
        EventLoopGroup master = new NioEventLoopGroup();
        EventLoopGroup slave = new NioEventLoopGroup();
        try {
            //创建服务器类
            ServerBootstrap server = new ServerBootstrap();
            server.group(master, slave)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            //获取管道
                            ChannelPipeline pipeline = socketChannel.pipeline();
                            pipeline.addLast(new HttpServerCodec());//http解编码
                            pipeline.addLast(new ChunkedWriteHandler());//对数据流写进行支持
                            //对httpMessage进行聚合处理，聚合成request或response
                            pipeline.addLast(new HttpObjectAggregator(1024 * 10));

                            //处理握手动作
                            //对于websocket来讲，都是以frame进行传输的，不同的数据类型对应的frame也不同
                            pipeline.addLast(new WebSocketServerProtocolHandler("/ws"));

                            //添加自定义处理器
                            pipeline.addLast(new SimpleChannelInboundHandler<TextWebSocketFrame>() {
                                @Override
                                protected void channelRead0(ChannelHandlerContext channelHandlerContext, TextWebSocketFrame textWebSocketFrame) throws Exception {
                                    chatService.dealWithChat(channelHandlerContext, textWebSocketFrame.text());
                                }
                            });
                        }
                    });
            ChannelFuture channelFuture = server.bind(port).sync();
            channelFuture.channel().closeFuture().sync();
            //System.out.println("netty服务器启动完成...");
        } finally {
            master.shutdownGracefully();
            slave.shutdownGracefully();
        }
    }
}
